﻿#region Usings

using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;

#endregion

namespace XPressify.Helpers
{
    public static class ObjectExtensions
    {
        /// <summary>
        ///   Turn anonymous object to dictionary
        /// </summary>
        /// <param name = "data"></param>
        /// <returns></returns>
        public static IDictionary<string, object> ToDictionary(this object data)
        {
            const BindingFlags attr = BindingFlags.Public | BindingFlags.Instance;
            return
                data.GetType().GetProperties(attr).Where(property => property.CanRead).ToDictionary(
                    property => property.Name, property => property.GetValue(data, null));
        }

        public static ViewDataDictionary ToViewDataDictionary(this object data)
        {
            var res = new ViewDataDictionary();
            foreach (var pair in data.ToDictionary())
            {
                res[pair.Key] = pair.Value;
            }
            return res;
        }
    }
}